Using MySql in ASP.Net

MySQL is one of the most commonly used database servers on the Internet, part of its popularity comes from tight integration with PHP, but ASP.net can also use it. Using the ODBC classes from the .NET framework, you can easily work with a MySQL database.

This tutorial will not install MySQL, nor will it cover SQL in general. It will focus on using MySQL with ASP.NET.

To start with using MySQL with ASP.NET, follow the next chapters we will cover the contents from the first connection in the database and much more.

The easiest way to use MySQL with ASP.NET is to use MySQL ODBC Connector with MySQL AB. If you are working, which is being hosted by a company that supports MySQL, maybe they already have it installed, but if you have your own code of MySQL on your own machine If you are testing with, you have to install it. MySQL Connector / ODBC 3.51 can be downloaded from this page: http://dev.mysql.com/downloads/connector/odbc/3.51.html

Once installed, you will be able to connect to your MySQL database server. It is quite easy to do this, but we will also need some data for testing. During the next chapters, we will use a table named test_users. You can find the SQL code to create and fill the table with the test data below. Run this function of your favorite MySQL client's SQL function, or use a command prompt to import it into a new or existing database

First of all, create a new project in Visual Studio for this. Secondly, let's store the connection information for the database at a time, so we can reuse all of our applications. We will do this with the web.config file. You can add it by clicking on the project name in Solution Explorer and selecting "Add new item". From the dialog that pops up, select the "Web Configuration File" Select Add, and the file will be added to your project. It will be opened automatically. Now, find that part and replace it with:


<connectionStrings>
  <add name="MySQLConnStr" connectionString="DRIVER={MySQL ODBC 3.51 Driver};Database=YourDatabase;Server=localhost;UID=YourUsername;PWD=YourPassword;"/>
</connectionStrings>

By doing so, we can access the connection string from all applications. You should change the 3 values ​​in it: Your database, your username, and your password are definitely replaced by the name of the database that you use, as well as the user for one of the MySQL database server users Name and password In the next chapter, I will show you how we get value and use it.

Here is the SQL code to create and fill our test table with some data:


CREATE TABLE `test_users` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(100) NOT NULL default '',
  `country` varchar(100) NOT NULL default '',
  PRIMARY KEY  (`id`)
);

INSERT INTO `test_users` VALUES (1,'John','USA');
INSERT INTO `test_users` VALUES (2,'Mark','Canada');
INSERT INTO `test_users` VALUES (3,'Lukas','Germany');
INSERT INTO `test_users` VALUES (4,'Ingrid','Sweden');